package com.cty.config;

import com.github.pagehelper.PageInterceptor;
import org.apache.ibatis.logging.slf4j.Slf4jImpl;
import org.apache.ibatis.session.AutoMappingBehavior;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;
import java.util.Properties;

/*
* 为什么将连接池与mapperConfig分开
* 因为mapperConfig的配置都是配置类，
* 配置类在项目启动时加载比@Value快，
* 会报空指针异常，分开写会缓存一下，
* 就不会报异常了
*
*
* */
@Configuration
public class mapperConfig {

    //用sqlSessionFactoryBean创建sqlSession
    @Bean
    public SqlSessionFactoryBean sqlSessionFactory(DataSource dataSource) {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();

        org.apache.ibatis.session.Configuration configuration =
                new org.apache.ibatis.session.Configuration();
        //mybatis的第二种方式 <settings>
        configuration.setMapUnderscoreToCamelCase(true);
        configuration.setLogImpl(Slf4jImpl.class);
        configuration.setAutoMappingBehavior(AutoMappingBehavior.FULL);
        sqlSessionFactoryBean.setConfiguration(configuration);
        //<别名>
        sqlSessionFactoryBean.setTypeAliasesPackage("com.cty.pojo");//传入包
        //插件
        PageInterceptor pageInterceptor = new PageInterceptor();//分页插件
        Properties properties = new Properties();
        properties.setProperty("helperDialect","mysql");
        pageInterceptor.setProperties(properties);//传入配置
        sqlSessionFactoryBean.setPlugins(pageInterceptor);
        //mybatis的第一种配置方式
//        Resource resource = new ClassPathResource("mybatis-config.xml");
//        sqlSessionFactoryBean.setConfigLocation(resource);
       sqlSessionFactoryBean.setDataSource(dataSource);

        return sqlSessionFactoryBean;
    }


    //用mapper扫描配置
    @Bean
    public MapperScannerConfigurer mapperScannerConfigurer() {
        MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
        //传入mapper接口所在的包(mapper接口与xml所在的共同包)
        mapperScannerConfigurer.setBasePackage("com.cty.mapper");
        return mapperScannerConfigurer;
    }

}
